package com.woniu.config;

import com.woniu.outlet.dao.PotentialMessageMapper;
import com.woniu.outlet.po.PotentialMessage;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class PotentialRabbitConfig {

    @Autowired
    private PotentialMessageMapper potentialMessageMapper;

    @Bean
    public RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory){

        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        rabbitTemplate.setConnectionFactory(connectionFactory);

        //转发消息到交换机
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                //如果消息成功的发送到交换机后，就修改消息的状态 如果失败了则不管
                if(ack){
                    //获取消息的id
                    Integer messageid=Integer.parseInt(correlationData.getId());
                    PotentialMessage potentialMessage = new PotentialMessage();
                    potentialMessage.setPotentialmessageId(messageid);
                    potentialMessage.setPotentialmessageStatus(1);

                    //更新消息的状态为已发送
                    potentialMessageMapper.updateByPrimaryKeySelective(potentialMessage);
                }
            }
        });

        //路由到队列当中，失败才触发，成功不触发
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int code, String text, String exchange, String routekey) {
                String correlationId = message.getMessageProperties().getCorrelationId();
                PotentialMessage potentialMessage = new PotentialMessage();
                potentialMessage.setPotentialmessageId(Integer.parseInt(correlationId));
                potentialMessage.setPotentialmessageStatus(0);
                //发送失败 更新消息的状态 为  未发送
                potentialMessageMapper.updateByPrimaryKeySelective(potentialMessage);
            }
        });

    return rabbitTemplate;
    }

}
